//
//  DetailGrabViewController.m
//  CloudMD
//
//  Created by apple on 16/2/18.
//  Copyright (c) 2016年 HuaZhengInfo. All rights reserved.
//

#import "DetailGrabViewController.h"
#import "DetailGrabTableViewCell.h"
#import "ImageGrabTableViewCell.h"
#import "GetOrderDetailModel.h"
#import "ImageModel.h"
#import "ImageTableViewCell.h"
#import "ShowImageViewController.h"
#import "XJAlbum.h"

@interface DetailGrabViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{

    UITableView * _tableView;
    NSMutableArray * _mainArray;
    NSMutableArray * _detailArray;
    NSMutableArray * _dataArray;
    NSMutableArray * _imageArray; //  图片数组
    GetOrderDetailModel * _detailModel;
    NSString * _state; // 返回状态
}
@property (nonatomic, assign) BOOL havePic;

@end

@implementation DetailGrabViewController

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
//    [self requestData];
//    [self requestImageData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 导航栏左按钮
    UIButton * leftButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, 10, 15) backImage:@"left_arrow" title:nil titleLableColcor:nil titleLabelFont:nil];
    [leftButton addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self creatTabelViewTitleView];
    
    // 初始化
    _dataArray = [NSMutableArray array];
    _mainArray = [NSMutableArray array];
    _detailArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    
    _ID = [[NSString alloc] init];
    _SYSCODE = [[NSString alloc] init];
    _state = @"SUCCESS";
    
    // 请求列表数据
    [self requestData];
    
    // 请求图片
    [self requestImageData];
    
    // 创建UI
    [self buildTableview];
    
}

- (void)startBlock {
    if (_refreshBlock) {
        _refreshBlock();
    }
}


#pragma mark -- 请求列表数据
- (void)requestData{

    _mainArray = [NSMutableArray arrayWithObjects:@"订单号:",@"问题类型:",@"问题区位:",@"问题描述:",@"资料:",@"提报时间:",nil];
    [_dataArray removeAllObjects];
//    NSUserDefaults * IdUser = [NSUserDefaults standardUserDefaults];
    _ID = [[NSUserDefaults standardUserDefaults] objectForKey:@"GUO"];
    NSArray * keyArray = @[@"ID",@"GUID",@"SYSCODE"];
    NSArray * valueArray = @[_ID,@"",@""];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,GetOrderDetail];
//    [SVProgressHUD showWithStatus:@"加载中..."];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            
            _detailModel = [[GetOrderDetailModel alloc] initWithDict:dataDict];
            [_dataArray addObject:_detailModel];
        }
        
        [_tableView reloadData];
//        [SVProgressHUD dismiss];
    } withTag:101];
}

#pragma mark -- 提交抢单数据
- (void)RequestGetData{

    NSArray * keyArray = @[@"GUID",@"USER_ID",@"USER_CODE",@"TYPE"];
    NSArray * valueArray = @[_GUID,USER_ID,USER_CODE,@""];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,GetOrderDo_URL];
    
//    [SVProgressHUD show];
//    [SVProgressHUD showWithStatus:@"加载中..."];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            
            _state = [dataDict objectForKey:@"STATUS"];
        }
        
//        [SVProgressHUD dismiss];
        if ([_state isEqualToString:@"SUCCESS"]) {
            
            [MBProgressHUD HUDShowMessage:@"抢单成功" addedToView:self.navigationController.view];
            [self.navigationController popToRootViewControllerAnimated:YES];
            [self startBlock];
        }else{
            
            [MBProgressHUD HUDShowMessage:@"抢单失败" addedToView:self.navigationController.view];
        }
    } withTag:101];
}
#pragma mark -- 请求图片数据
- (void)requestImageData{

//    NSUserDefaults * IdUser = [NSUserDefaults standardUserDefaults];
    [_imageArray removeAllObjects];
    _ID = [[NSUserDefaults standardUserDefaults] objectForKey:@"GUO"];
    NSArray * keyValue = @[@"ID",@"MODULE"];
    NSArray * valueValue = @[_ID,@"INSPECTION"];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueValue forKeys:keyValue];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,DownloadAttachment_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        self.havePic = YES;
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            
            ImageModel * model = [[ImageModel alloc] initWith:dataDict];
            [_imageArray addObject:model.WSPATH];
            
        }
        NSUserDefaults * infoUser = [NSUserDefaults standardUserDefaults];
        [infoUser setObject:_imageArray forKey:@"INFO"];
        [_tableView reloadData];
    } withTag:101];
}

#pragma mark -- 创建Tableview
- (void)buildTableview{

    _tableView = [[UITableView alloc] init];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [_tableView addGestureRecognizer:tapGesture];
    
    _tableView.rowHeight = SCR_H / 7;
    CGFloat h = _tableView.rowHeight * 5;
    _tableView.frame = CGRectMake(0, 0, SCR_W, h);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    //隐藏分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    // 抢单按钮
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCR_W/2, 40)];
    button.center = CGPointMake(SCR_W/2, CGRectGetMaxY(_tableView.frame)+15);
    [button setBackgroundImage:[UIImage imageNamed:@"3在线下单"] forState:UIControlStateNormal];
    [button setTitle:@"我要抢单" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickGrab) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    CGPoint tapLocation = [tap locationInView:_tableView];
    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:tapLocation];
    if (indexPath.row == 4) {
        ImageTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        for (UIView *view in cell.contentView.subviews) {
            if (CGRectContainsPoint(view.frame, pointInCell)) {
                if (_imageArray.count > 0) {
                    XJAlbum *imageShowVC = [[XJAlbum alloc] initWithImgUrlArr:_imageArray CurPage:view.tag];
                    imageShowVC.photoFrame = CGRectMake(0, 0, SCR_W, SCR_H);
                    [self.navigationController presentViewController:imageShowVC animated:YES completion:nil];
                }
            }
        }
    }
}


#pragma mark -- 创建导航栏标题
- (void)creatTabelViewTitleView{

    UIView * titleView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, 80, 45) backColor:[UIColor clearColor]];
    UILabel * mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, titleView.frame.size.height)];
    mainLabel.textAlignment = NSTextAlignmentCenter;
    mainLabel.text = @"订单详情";
    mainLabel.textColor = [UIColor whiteColor];
    mainLabel.font = [UIFont systemFontOfSize:18];
    [titleView addSubview:mainLabel];
    
    UILabel * detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(mainLabel.frame), titleView.frame.size.width, titleView.frame.size.height * 0.4)];
    detailLabel.text = _detailModel.SYSCODE;
    detailLabel.textAlignment = NSTextAlignmentCenter;
    detailLabel.textColor = [UIColor whiteColor];
    detailLabel.font = [UIFont systemFontOfSize:15];
//    [titleView addSubview:detailLabel];
    
    self.navigationItem.titleView = titleView;
    
}

#pragma mark -- TableviewDelegate And DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _mainArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 4) {
        NSString * ID = @"cell";
        
        ImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.havePic) {
            cell.imageArray = _imageArray;
        }
        return cell;
        
    }else{
        NSString * ID = @"cellId";
        DetailGrabTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[DetailGrabTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            
        }
        cell.mainLabel.text = _mainArray[indexPath.row];
        if (indexPath.row == 0) {
//            cell.mainLabel.text = _mainArray[indexPath.row];
            cell.detailLabel.text = _detailModel.SYSCODE;
        }
        if (indexPath.row == 1) {
            
//            cell.mainLabel.text = _mainArray[indexPath.row];
            cell.detailLabel.text = _detailModel.TYPE_NAME;
        }
        if (indexPath.row == 2) {
//            cell.mainLabel.text = _mainArray[indexPath.row];
            cell.detailLabel.text = _detailModel.GRID_NAME;
        }
        if (indexPath.row == 3) {
//            cell.mainLabel.text = _mainArray[indexPath.row];
            cell.detailLabel.text = _detailModel.REMARK;
            CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
            CGSize expectSize = [cell.detailLabel sizeThatFits:maximumLabelSize];
            cell.detailLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.mainLabel.frame)+10, cell.frame.size.width-20, expectSize.height);
        }
        if (indexPath.row == 5) {
//            cell.mainLabel.text = _mainArray[indexPath.row];
            cell.detailLabel.text = _detailModel.DATE;
        }
        
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    return cell;
    }
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    if (indexPath.row == 4) {
//        if (_imageArray.count > 0) {
////            ShowImageViewController * showVC = [[ShowImageViewController alloc] init];
////            showVC.imageArray = _imageArray;
////            [self.navigationController pushViewController:showVC animated:YES];
//            
//            XJAlbum *imageShowVC = [[XJAlbum alloc] initWithImgUrlArr:_imageArray CurPage:0];
//            imageShowVC.photoFrame = CGRectMake(0, 0, SCR_W, SCR_H);
//            [self.navigationController presentViewController:imageShowVC animated:YES completion:nil];
//        }
//    }
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 3) {
        UILabel *tmpLabel = [[UILabel alloc] init];
        tmpLabel.font = [UIFont systemFontOfSize:18];
        tmpLabel.numberOfLines = 0;
        tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
        tmpLabel.text = _detailModel.REMARK;
        CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
        CGSize expectSize = [tmpLabel sizeThatFits:maximumLabelSize];
        return SCR_H/9 * 0.4 + expectSize.height + 10;
    }
    if (indexPath.row == 4) {
        if (_imageArray.count < 6) {
            return SCR_H / 5;
        } else {
            return SCR_H * 0.33;
        }
    }else{
        return SCR_H / 9;
    }
}

#pragma mark -- 点击抢单
- (void)clickGrab{
    
    [self alertError:@"确认抢单？"];
    
}

- (void)clickLeft{

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 弹框提示
- (void)alertError:(NSString *)error{
    // 1.弹框
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:error delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        [self RequestGetData];
    }
}

#pragma  mark -- 刷新
- (void)setupRefresh{

//    [_tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
//    [_tableView addFooterWithTarget:self action:@selector(footerRefreshing)];
    
}

- (void)headerRefreshing{

    [self refrshing];
    [self requestData];

}


- (void)footerRefreshing{

    [self refrshing];
    [self requestData];
}

- (void)refrshing{

//    [_tableView headerEndRefreshing];
//    [_tableView footerEndRefreshing];
}

@end
